package com.wolfking.converter.freemarker;

import com.wolfking.jeesite.freemarker.FreemarkerMethod;
import freemarker.template.SimpleDate;
import freemarker.template.TemplateMethodModelEx;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@FreemarkerMethod("dateDifference")
public class DateDifferenceMethod implements TemplateMethodModelEx {
    @Override
    public Object exec(List list) {
        if (list.size() == 3) {
            SimpleDateFormat sdf = new SimpleDateFormat(list.get(0).toString());
            try {
                Date start = list.get(1) instanceof SimpleDate ? ((SimpleDate) list.get(1)).getAsDate() : sdf.parse(list.get(1).toString());
                Date end = list.get(2) instanceof SimpleDate ? ((SimpleDate) list.get(2)).getAsDate() : sdf.parse(list.get(2).toString());
                return end.getTime() - start.getTime();
            } catch (ParseException e) {
                throw new RuntimeException("日期解析错误");
            }
        } else if (list.size() == 2) {
            Date start = ((SimpleDate) list.get(0)).getAsDate();
            Date end = ((SimpleDate) list.get(1)).getAsDate();
            return end.getTime() - start.getTime();
        } else {
            throw new RuntimeException("参数必须是2个");
        }
    }
}
